package zsc.ruanc.practicaltraining.config.interceptor;


import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import zsc.ruanc.practicaltraining.exception.ApiException;
import zsc.ruanc.practicaltraining.mapper.Redis;
import zsc.ruanc.practicaltraining.utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class tokenInterceptor implements HandlerInterceptor {

    @Autowired
    private Redis redis;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        System.out.println("----------------------------------------------");
        System.out.println("-----------token拦截器开始执行----------------------");
        System.out.println("----------------------------------------------");



        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }


        String token = httpServletRequest.getHeader("token");
        System.out.println(token);

        if (token == null) {
            throw new ApiException(-9, "请在请求头添加token字段，添加token之后在访问");
        }

        int id = (int) TokenUtils.getRedisKey(token);
        String key = (String) redis.get(String.valueOf(id));
        if (key == null) {
            throw new ApiException(-10, "请重新登录");
        }

        // 验证有效性
        DecodedJWT decodedJWT = TokenUtils.deToken(token, key);

        String ip = httpServletRequest.getRemoteAddr();
        String role = decodedJWT.getClaim("role").asString();
        String name = decodedJWT.getSubject();
        System.out.println(name);
        System.out.println(ip);
        System.out.println(id);
        System.out.println(role);
//        httpServletRequest.setAttribute("ip", ip);
        httpServletRequest.setAttribute("id", id);
        httpServletRequest.setAttribute("name", name);
        // 用户的身份字符串
        httpServletRequest.setAttribute("role", role);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}
